﻿using RestSharp;
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;

namespace PushNotificationsHelper
{
    public class WNSAuthHelper
    {
        public static WNSAuthToken GetAccessToken(string key, string sid)
        {
            var client = new RestClient("https://login.live.com/accesstoken.srf");
            var request = new RestRequest(Method.POST)
                .AddParameter("grant_type", "client_credentials")
                .AddParameter("client_id", sid)
                .AddParameter("client_secret", key)
                .AddParameter("scope", "notify.windows.com");
            var response = client.Execute<WNSAuthToken>(request);
            return response.Data;

            //var urlEncodedSecret = HttpUtility.UrlEncode(key);

            //var urlEncodedSid = HttpUtility.UrlEncode(sid);
            //var body = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);

            //string response;
            //using (var client = new WebClient())
            //{
            //    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            //    response = client.UploadString("https://login.live.com/accesstoken.srf", body);
            //}

            //using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response)))
            //{
            //    var ser = new DataContractJsonSerializer(typeof(WNSAuthToken));
            //    var wnsAuthToken = (WNSAuthToken)ser.ReadObject(ms);
            //    return wnsAuthToken;
            //}
        }



        //private WNSAuthToken GetAccessToken()
        //{
        //    var urlEncodedSecret = HttpUtility.UrlEncode(SecretKey);
        //    var urlEncodedSid = HttpUtility.UrlEncode(Sid);

        //    var body =
        //      String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);

        //    string response;
        //    using (var client = new WebClient())
        //    {
        //        client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        //        response = client.UploadString("https://login.live.com/accesstoken.srf", body);
        //    }

        //    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response)))
        //    {
        //        var ser = new DataContractJsonSerializer(typeof(WNSAuthToken));
        //        var oAuthToken = (WNSAuthToken)ser.ReadObject(ms);
        //        return oAuthToken;
        //    }
        //}

    }
}
